package com.myapp.api.controller;

import com.myapp.api.entity.Admin;
import com.myapp.api.entity.Student;
import com.myapp.api.entity.Teacher;
import com.myapp.api.service.AdminService;
import com.myapp.api.service.StudentService;
import com.myapp.api.service.TeacherService;
import com.myapp.api.tools.JWTUtils;
import com.myapp.api.tools.JsonResult;
import com.myapp.api.tools.ResultStatus;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@Api(value = "UserController", description = "获取用户信息,包括管理员信息,学生信息,教师信息")
@RestController
@RequestMapping(value = "/user", produces = "application/json;charset=UTF-8")
public class UserController {
    @Autowired
    private AdminService service1;
    @Autowired
    private StudentService service2;
    @Autowired
    private TeacherService service3;

    @GetMapping("/current")
    public ResponseEntity<?> getCurrent(HttpServletRequest request) {
        String authHeader = request.getHeader(JWTUtils.TOKEN_HEADER);
        Claims claims = JWTUtils.parseJWT(authHeader);
        String account = (String) claims.get("account");
        String role = (String) claims.get("role");

        if (role.equals("ADMIN")) {
            Admin admin = service1.getAdminByAccount(account);
            HttpStatus status = HttpStatus.OK;
            return new ResponseEntity<Admin>(admin, status);
        } else if (role.equals("STUDENT")) {
            Student student = service2.getStudentBySid(account);
            HttpStatus status = HttpStatus.OK;
            return new ResponseEntity<Student>(student, status);
        } else if (role.equals("TEACHER")) {
            Teacher teacher = service3.getTeacherByTid(account);
            HttpStatus status = HttpStatus.OK;
            return new ResponseEntity<Teacher>(teacher, status);
        } else {
            HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
            JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, "不存在的角色：" + role);
            return new ResponseEntity<JsonResult>(result, status);
        }
    }
}
